package cn.wizzer.redis;

import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;

/**
 * redisTemplateBean
 */
@IocBean
public class RedisConfig {
    @Inject("java:$conf.get('redis.database')")
    private Integer database;

    @Inject("java:$conf.get('redis.host')")
    private String host;

    @Inject("java:$conf.get('redis.password')")
    private String password;

    @Inject("java:$conf.get('redis.port')")
    private Integer port;

    @Inject("java:$conf.get('redis.timeout')")
    private Integer timeout;

    @Inject("java:$conf.get('redis.max_redir')")
    private Integer maxIdle;

    @IocBean
    public JedisPoolConfig jedisPoolConfig(){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(this.maxIdle);
//        poolConfig.setMinIdle(this.minIdle);
        poolConfig.setTestOnCreate(true);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        poolConfig.setTestWhileIdle(true);
        return poolConfig;
    }
    @IocBean
    public JedisConnectionFactory jedisConnectionFactory(){

        JedisPoolConfig config = jedisPoolConfig();
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(config);
        //region 手动注入JedisShardInfo.
        JedisShardInfo jedisShardInfo = new JedisShardInfo(this.host,this.port);
        jedisShardInfo.setPassword(this.password);
        jedisShardInfo.setConnectionTimeout(this.timeout);
        jedisShardInfo.getPort();
        jedisConnectionFactory.setShardInfo(jedisShardInfo);
        //endregion
        //region 初始化jedis参数
        jedisConnectionFactory.setDatabase(this.database);
        jedisConnectionFactory.setHostName(this.host);
        jedisConnectionFactory.setPassword(this.password);
        jedisConnectionFactory.setPort(this.port);
        jedisConnectionFactory.setTimeout(this.timeout);
        //endregion
        return jedisConnectionFactory;
    }
    @IocBean
    public StringRedisTemplate stringRedisTemplate(){
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(jedisConnectionFactory());
        stringRedisTemplate.afterPropertiesSet();
        return stringRedisTemplate;
    }

}
